<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <slot name="left" />
        </template>

        <template #right>
          <el-button type="warning" size="small" @click="$router.push('/import?type=user')">excel导入</el-button>
          <el-button type="danger" size="small" @click="handleDownload">excel导出</el-button>
          <el-button type="primary" size="small" @click="nowStaff">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list.rows">
          <el-table-column label="序号" type="index" :index="indexDecide" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formOfEmployment" />
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry">
            <template #default="{row}">
              {{ TimeChange(row.timeOfEntry) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="280">
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">分配角色</el-button>
              <el-button type="text" size="small" @click="DeleteFunction(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-pagination
          layout="prev, pager, next"
          :total="list.total"
          @current-change="handleCurrentChange"
        />
      </el-card>
      <addEmployee :show-dialog.sync="showDialog" />
    </div>
  </div>
</template>

<script>
import { getEmployeeListApi, DeletionOfEmployeeAPI } from '@/api/employee'
import dayjs from 'dayjs'
import employees from '@/constant/employees'
import addEmployee from './components/add-employee.vue'
export default {
  components: {
    addEmployee
  },
  data() {
    return {
      page: 1,
      pagesize: 10,
      list: [],
      showDialog: false
    }
  },
  created() {
    this.RoleList()
  },
  methods: {
    // 获取数据
    async RoleList() {
      const { data: res } = await getEmployeeListApi(this.page, this.pagesize)
      this.list = res
      // console.log(res)
    },
    // 列表序号优化
    indexDecide(index) {
      return (this.page - 1) * this.pagesize + index + 1
    },
    // 分页绑定
    handleCurrentChange(val) {
      this.page = val
      this.RoleList()
    },
    // 删除功能
    DeleteFunction(id) {
      // console.log(id)
      this.$confirm('确认要删除吗？', '温馨提示').then(async() => {
        const res = await DeletionOfEmployeeAPI(id)
        if (this.list.length === 1 && this.page > 1) {
          this.page--
        }
        this.$message.success(res.message)
        console.log(res)
        this.RoleList()
      }).catch(() => {})
    },
    // 时间格式更改
    TimeChange(value) {
      return value ? dayjs(value).format('YYYY-MM-DD') : ''
    },
    // 格式化聘用形式
    formOfEmployment(value) {
      const hireType = employees.hireType
      const obj = hireType.find(item => item.id === +value.formOfEmployment)
      return obj ? obj.value : '未知'
    },
    // 点击新增员工
    nowStaff() {
      this.showDialog = true
    },
    // 点击导出数据
    async handleDownload() {
      // 获取到数据
      const { data: { rows }} = await getEmployeeListApi(1, this.list.total)
      // console.log(rows)
      // 定义顺序
      const headersArr = ['姓名', '手机号', '入职日期', '聘用形式', '转正日期', '工号', '部门']
      // 定义转换样式
      const headersRelations = {
        '姓名': 'username',
        '手机号': 'mobile',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const lists = []
      // 将获取到的数组拿到每一项
      rows.forEach(item => {
        const arr = []
        // 再便利顺序的每一项
        headersArr.forEach(key => {
          // 获取到转换样式相对应的顺序
          const res = headersRelations[key]
          // 根据转换样式的顺序获取要用到的数组
          let value = item[res]
          // 判断是聘用形式
          if (res === 'formOfEmployment') {
            // 调用对比的数组
            const hireType = employees.hireType
            // 判断等于对比里的哪个数
            const obj = hireType.find(item => item.id === +value)
            // 输出内容
            value = obj ? obj.value : '未知'
          }
          if (['correctionTime', 'timeOfEntry'].includes(res)) {
            value = this.TimeChange(value)
          }
          arr.push(value)
        })
        lists.push(arr)
      })
      console.log(lists)
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: headersArr, // 表头 必填
          data: lists, // 具体数据 必填
          filename: 'excel-list', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    }
  }

}
</script>

<style lang="scss" scoped>
.page-tools {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .tips {
    line-height: 34px;
    padding: 0px 15px;
    border-radius: 5px;
    border: 1px solid rgba(145, 213, 255, 1);
    background: rgba(230, 247, 255, 1);
    i {
      margin-right: 10px;
      color: #409eff;
    }
  }
}
</style>
